package examples.ejb.ejb20.basic.profile;

import javax.ejb.CreateException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import weblogic.ejbgen.*;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.Set;


/**
 * ProfileBean is a stateless Session Bean. This bean illustrates:
 * <ul>
 * <li> No persistence of state between calls to the Session Bean
 * <li> Looking up values from the Environment
 * </ul>
 *
 * @author Copyright (c) 1999-2008 by BEA Systems, Inc. All Rights Reserved.
 */
@EnvEntries({
    @EnvEntry(name = "WEBL",
              type = "java.lang.Double",
              value = "10.0"),
    @EnvEntry(name = "minLimit",
              type = "java.lang.Integer",
              value = "6"),
    @EnvEntry(name = "maxLimit",
              type = "java.lang.Integer",
              value = "15")
})
@FileGeneration(remoteClass = Constants.Bool.TRUE,
                localHome = Constants.Bool.FALSE,
                remoteHome = Constants.Bool.TRUE,
                remoteClassName = "Profile",
                remoteHomeName = "ProfileHome",
                localClass = Constants.Bool.FALSE)
@JarSettings(ejbClientJar = "ejb20_basic_profile_client.jar")
@JndiName(remote = "ejb20-profile-ProfileHome")
@Session(maxBeansInFreePool = "1000",
         initialBeansInFreePool = "0",
         transTimeoutSeconds = "0",
         type = Session.SessionType.STATELESS,
         defaultTransaction = Constants.TransactionAttribute.REQUIRED,
         ejbName = "profile",
         enableCallByReference = Constants.Bool.TRUE)
public class ProfileBean implements SessionBean {

  private static final boolean VERBOSE = false;
  private SessionContext ctx;
  private int minLimit;
  private int maxLimit;
  public static final String PROFILEINPUTTEXT = "C:/bea/wlserver_10.3/profile_input.txt";
  public static final String ADDRESSTEXT = "C:/bea/wlserver_10.3/address.txt";
  
//  private static List<String[]> listOfNames = new ArrayList<String[]>();
  private static final Hashtable<String,String> profileTable = new Hashtable<String,String>();
  static {
		try {
			loadHashTable();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
  }
	
  @RemoteMethod()
   public Hashtable getProfileTable(){
	   return profileTable;
   }
  @RemoteMethod()
  public String getPROFILEINPUTTEXT(){
	   return PROFILEINPUTTEXT;
  }
  @RemoteMethod()
  public String getADDRESSTEXT(){
	   return ADDRESSTEXT;
  }
	private static void loadHashTable() throws FileNotFoundException{
		String line=null;
		Pattern extPattern=Pattern.compile("(.*)\\*(.*)\\*",Pattern.CASE_INSENSITIVE);
		BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(
				new FileInputStream(ADDRESSTEXT))));	
		try {
			while ((line=reader.readLine())!=null){
				Matcher matcher = extPattern.matcher(line.trim());
				while (matcher.find()){
					profileTable.put( matcher.group(1),  matcher.group(2));
				}
			}		
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RemoteMethod()
	public String getAddress (String uid){
		String theAddress = profileTable.get(uid);
		return(theAddress);
	}
	
	public static void writeProfileTable(){
			File newFile = new File(ADDRESSTEXT);
			PrintWriter out;
			try {
				out = new PrintWriter(newFile);
				for (String thisKey : profileTable.keySet()){
					out.println(thisKey+"*"+profileTable.get(thisKey)+"*");
				}
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} 
		}  
	
	@RemoteMethod()
	public boolean addProfile (String uid, String address) {
		if (getAddress(uid)!=null){
			profileTable.remove(uid);
		}
		profileTable.put(uid,address);	
		writeProfileTable();
		return(false);
	}
  
  // You might also consider using WebLogic's log service
  private void log(String s) {
    if (VERBOSE) System.out.println(s);
  } 
  
  /**
   * This method is required by the EJB Specification,
   * but is not used by this example.
   *
   */
  public void ejbActivate() {
    log("ejbActivate called");
  }

  /**
   * This method is required by the EJB Specification,
   * but is not used by this example.
   *
   */
  public void ejbRemove() {
    log("ejbRemove called");
  }

  /**
   * This method is required by the EJB Specification,
   * but is not used by this example.
   *
   */
  public void ejbPassivate() {
    log("ejbPassivate called");
  }

  /**
   * Sets the session context.
   *
   * @param ctx               SessionContext Context for session
   */
  public void setSessionContext(SessionContext ctx) {
    log("setSessionContext called");
    this.ctx = ctx;
  }

  /**
   * This method corresponds to the create method in the home interface
   * "ProfileHome.java".
   * The parameter sets of the two methods are identical. When the client calls
   * <code>ProfileHome.create()</code>, the container allocates an instance of 
   * the EJBean and calls <code>ejbCreate()</code>.
   *
   * @exception               javax.ejb.CreateException if there is
   *                          a communications or systems failure
   * @see                     examples.ejb.ejb20.basic.statelessSession.Trader
   */
  public void ejbCreate () throws CreateException {

  }


}
